strpad in Javascript?`

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Merlin

    strpad in Javascript?`

    Hi there,

    I am wondering if there is a function doing the same as in PHP strpad()?

    What I want to do is to make sure a string is always 2 characters long. If it is
    one character the function should add a 0 in front.

    Eg: make a "04" out of "4"

    Is this possible?

    Thank you for any hint,

    Merlin
  • Mick White

    #2
    Re: strpad in Javascript?`

    Merlin wrote:
    [color=blue]
    > Hi there,
    >
    > I am wondering if there is a function doing the same as in PHP strpad()?
    >
    > What I want to do is to make sure a string is always 2 characters long.
    > If it is one character the function should add a 0 in front.
    >
    > Eg: make a "04" out of "4"
    >
    > Is this possible?
    >
    > Thank you for any hint,
    >
    > Merlin[/color]

    function strpad(val){
    return (!isNaN(val) && val.toString(). length==1)?"0"+ val:val;
    }
    Or as a method of the string:
    String.prototyp e.strpad=functi on(){
    return (!isNaN(this) && this.toString() .length==1)?"0" +this:this;
    }

    Mick

    Comment

    • Merlin

      #3
      Re: strpad in Javascript?`

      wow! Thank you Mick. I did not think that there is so much programming to do for
      that.

      Merlin


      Mick White wrote:
      [color=blue]
      > Merlin wrote:
      >[color=green]
      >> Hi there,
      >>
      >> I am wondering if there is a function doing the same as in PHP strpad()?
      >>
      >> What I want to do is to make sure a string is always 2 characters
      >> long. If it is one character the function should add a 0 in front.
      >>
      >> Eg: make a "04" out of "4"
      >>
      >> Is this possible?
      >>
      >> Thank you for any hint,
      >>
      >> Merlin[/color]
      >
      >
      > function strpad(val){
      > return (!isNaN(val) && val.toString(). length==1)?"0"+ val:val;
      > }
      > Or as a method of the string:
      > String.prototyp e.strpad=functi on(){
      > return (!isNaN(this) && this.toString() .length==1)?"0" +this:this;
      > }
      >
      > Mick[/color]

      Comment

      • Robert

        #4
        Re: strpad in Javascript?`

        In article <2l05jcF6vs65U1 @uni-berlin.de>, Merlin <news.groups@gm x.de>
        wrote:
        [color=blue]
        > Hi there,
        >
        > I am wondering if there is a function doing the same as in PHP strpad()?
        >
        > What I want to do is to make sure a string is always 2 characters long. If it
        > is
        > one character the function should add a 0 in front.
        >
        > Eg: make a "04" out of "4"
        >[/color]

        You need to write it yourself. You may want to put in some error
        checking.

        Here is an example:

        <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
        <html>
        <head>
        <title>Format Number</title>

        <script type="text/javascript">
        function formatNumber(nu m)
        {
        var displayNumber = num

        if (displayNumber< = 9)
        displayNumber = "0" + displayNumber;
        return displayNumber;
        }
        </script>

        </head>
        <body
        onload="alert(f ormatNumber(5)) ;">
        <p>
        Format a number.</p>
        </body>
        </html>

        Comment

        • Dr John Stockton

          #5
          Re: strpad in Javascript?`

          JRS: In article <BGBGc.16193$bp 1.4228@twister. nyroc.rr.com>, seen in
          news:comp.lang. javascript, Mick White <mwhite13@BOGUS rochester.rr.co m>
          posted at Tue, 6 Jul 2004 17:53:37 :[color=blue]
          >Merlin wrote:
          >[color=green]
          >> Hi there,
          >>
          >> I am wondering if there is a function doing the same as in PHP strpad()?
          >>
          >> What I want to do is to make sure a string is always 2 characters long.
          >> If it is one character the function should add a 0 in front.
          >>
          >> Eg: make a "04" out of "4"
          >>
          >> Is this possible?
          >>
          >> Thank you for any hint,
          >>
          >> Merlin[/color]
          >
          >function strpad(val){
          >return (!isNaN(val) && val.toString(). length==1)?"0"+ val:val;
          >}
          >Or as a method of the string:
          >String.prototy pe.strpad=funct ion(){
          >return (!isNaN(this) && this.toString() .length==1)?"0" +this:this;
          >}[/color]

          Published code should ALWAYS be indented according to structure.

          I see no need to check with isNaN; if someone wants to add a leading
          zero, (a) it is permissible to do this to entities which are not decimal
          numbers (e.g. to Hex number strings), (b) if the entity is not like a
          number, there's probably a bigger mistake somewhere, and an error here
          could be helpful.


          For converting a Number to a string of at least two digits representing
          the value,
          function LZ(x) { return (x<0||x>=10?"": "0") + x }

          Above, function strpad, if given a Number, returns either a Number or a
          String. This could cause later confusion. If a zero is added, there
          are two conversions of val to String.

          These might be better; String is probably cheap when applied to a string
          :-
          function lz(s) { var t = String(s)
          return t.length==1 ? "0"+t : t } // or <2 ??

          function lz(s) { var t
          return (t = String(s)).leng th==1 ? "0"+t : t } // ??

          --
          © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
          <URL:http://jibbering.com/faq/> JL / RC : FAQ for news:comp.lang. javascript
          <URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
          <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.

          Comment

          • Mick White

            #6
            Re: strpad in Javascript?`

            Dr John Stockton wrote:
            [color=blue]
            > JRS: In article <BGBGc.16193$bp 1.4228@twister. nyroc.rr.com>, seen in
            > news:comp.lang. javascript, Mick White <mwhite13@BOGUS rochester.rr.co m>
            > posted at Tue, 6 Jul 2004 17:53:37 :[/color]
            [color=blue][color=green]
            >>function strpad(val){
            >>return (!isNaN(val) && val.toString(). length==1)?"0"+ val:val;
            >>}
            >>Or as a method of the string:
            >>String.protot ype.strpad=func tion(){
            >>return (!isNaN(this) && this.toString() .length==1)?"0" +this:this;
            >>}[/color]
            >
            >
            > Published code should ALWAYS be indented according to structure.[/color]

            This is surely a matter of personal preference, flush left presentation
            doesn't suffer as much from the display quirks of many media as do
            indented, tabbed, "n" spaced or <pre> markup. IMO.
            [color=blue]
            >
            > I see no need to check with isNaN; if someone wants to add a leading
            > zero, (a) it is permissible to do this to entities which are not decimal
            > numbers (e.g. to Hex number strings), (b) if the entity is not like a
            > number, there's probably a bigger mistake somewhere, and an error here
            > could be helpful.[/color]

            A good point, especially that of generating an error.

            [color=blue]
            >
            >
            > For converting a Number to a string of at least two digits representing
            > the value,
            > function LZ(x) { return (x<0||x>=10?"": "0") + x }
            >
            > Above, function strpad, if given a Number, returns either a Number or a
            > String. This could cause later confusion. If a zero is added, there
            > are two conversions of val to String.[/color]

            I am loath to change the type of an object that undergoes no change,
            e.g. if the function is passed something that evaluates to the Number
            22, I don't want to spit out "22", although it really matters little, I
            suppose.
            [color=blue]
            >
            > These might be better; String is probably cheap when applied to a string
            > :-
            > function lz(s) { var t = String(s)
            > return t.length==1 ? "0"+t : t } // or <2 ??
            >
            > function lz(s) { var t
            > return (t = String(s)).leng th==1 ? "0"+t : t } // ??[/color]

            lz("K") returns "0K", but it's not OK, at least in my book. And I like
            the function to be somewhat descriptive, "strpad()" is a little obscure.

            function addLeadingZeroT oSingleDigitIfN eeded(num){
            // Now we're cooking
            // Test for Number, generate an error (visible to the user) upon failure
            // Deal with negative numbers, or not?
            // If it's a positive Number greater than 9, return it untouched
            // Disgorge the value with the leading zero, if needed.
            }

            If you're dealing with user entry, you know the rest....

            Mick

            Comment

            • Lee

              #7
              Re: strpad in Javascript?`

              Mick White said:[color=blue]
              >
              >Dr John Stockton wrote:[/color]
              [color=blue][color=green]
              >> Published code should ALWAYS be indented according to structure.[/color]
              >
              >This is surely a matter of personal preference, flush left presentation
              >doesn't suffer as much from the display quirks of many media as do
              >indented, tabbed, "n" spaced or <pre> markup. IMO.[/color]

              None of the display quirks that I've ever seen make code
              as unreadable as flush left, IMO.

              Comment

              • Mick White

                #8
                Re: strpad in Javascript?`

                Lee wrote:
                [color=blue]
                > Mick White said:
                >[color=green]
                >>Dr John Stockton wrote:[/color]
                >
                >[color=green][color=darkred]
                >>>Published code should ALWAYS be indented according to structure.[/color]
                >>
                >>This is surely a matter of personal preference, flush left presentation
                >>doesn't suffer as much from the display quirks of many media as do
                >>indented, tabbed, "n" spaced or <pre> markup. IMO.[/color]
                >
                >
                > None of the display quirks that I've ever seen make code
                > as unreadable as flush left, IMO.
                >[/color]

                You're not from a background in C++ are you? But both you and I agree
                that it's a matter of opinion....
                I have no problem with those who format their code with tabs or
                two-by-fours or whatever, but the code that I write is, for the most
                part, for my own consumption. There is a place for AR folks in
                programming, organization is very important.

                Important to me:
                Meaningful variable names.(Thanks to Dr. S for the prod)
                if(Boolean){cod e;} Always use braces after conditional
                Break out of loop/function asap.
                Efficiency of the code (lot to learn here)

                I must admit that 15 closing braces cascading diagonally across the page
                appeals to my sense of aesthetics.

                Mick



                Comment

                • Lee

                  #9
                  Re: strpad in Javascript?`

                  Mick White said:[color=blue]
                  >
                  >Lee wrote:
                  >[color=green]
                  >> Mick White said:
                  >>[color=darkred]
                  >>>Dr John Stockton wrote:[/color]
                  >>
                  >>[color=darkred]
                  >>>>Published code should ALWAYS be indented according to structure.
                  >>>
                  >>>This is surely a matter of personal preference, flush left presentation
                  >>>doesn't suffer as much from the display quirks of many media as do
                  >>>indented, tabbed, "n" spaced or <pre> markup. IMO.[/color]
                  >>
                  >>
                  >> None of the display quirks that I've ever seen make code
                  >> as unreadable as flush left, IMO.
                  >>[/color]
                  >
                  >You're not from a background in C++ are you? But both you and I agree
                  >that it's a matter of opinion....
                  >I have no problem with those who format their code with tabs or
                  >two-by-fours or whatever, but the code that I write is, for the most
                  >part, for my own consumption. There is a place for AR folks in
                  >programming, organization is very important.[/color]

                  C++ hasn't had much influence on my style. My first ten or so
                  years of coding was mostly FORTRAN, COBOL and Pascal, with a
                  touch each of LISP and Unix scripting. My second ten was mostly
                  C and Perl. More recently, my compiled code has been Java and
                  my scripting has mostly been Javascript.

                  You'll find that most programmers prefer some visual structure
                  to code. If you work in a situation where you have to share
                  your code with others (this forum, for example), you may find
                  that you have to have to adapt to the consensus standards.

                  [color=blue]
                  >Important to me:
                  >Meaningful variable names.(Thanks to Dr. S for the prod)
                  >if(Boolean){co de;} Always use braces after conditional
                  >Break out of loop/function asap.
                  >Efficiency of the code (lot to learn here)[/color]

                  Add ease of maintenance and debugging, and you may appreciate
                  the advantages of lining up your brackets in a way that shows
                  which one closes which block.

                  Comment

                  • Dr John Stockton

                    #10
                    Re: strpad in Javascript?`

                    JRS: In article <CJZGc.16948$bp 1.3027@twister. nyroc.rr.com>, seen in
                    news:comp.lang. javascript, Mick White <mwhite13@BOGUS rochester.rr.co m>
                    posted at Wed, 7 Jul 2004 21:15:14 :[color=blue]
                    >Dr John Stockton wrote:[/color]
                    [color=blue][color=green]
                    >> Published code should ALWAYS be indented according to structure.[/color]
                    >
                    >This is surely a matter of personal preference, flush left presentation
                    >doesn't suffer as much from the display quirks of many media as do
                    >indented, tabbed, "n" spaced or <pre> markup. IMO.[/color]

                    For code which will only be read personally, agreed (I do not here mean
                    published to include ordinary usage in Web pages). For code written
                    professionally, ISTM that one should accommodate the preferences of co-
                    workers, and think of successors. Code presented to the public, such as
                    code in News, should accord with public preference; and the general
                    judgement is as I wrote.

                    Media that cannot preserve spaces are unworthy of consideration.

                    Code presented in News for public enlightenment should be indented, to
                    show good practice; code presented in News for debugging should be
                    indented, for ease of reading. Equally, code should normally be
                    "paragraphe d", with for example functions separated by blank lines.

                    [color=blue][color=green]
                    >> For converting a Number to a string of at least two digits representing
                    >> the value,
                    >> function LZ(x) { return (x<0||x>=10?"": "0") + x }
                    >>
                    >> Above, function strpad, if given a Number, returns either a Number or a
                    >> String. This could cause later confusion. If a zero is added, there
                    >> are two conversions of val to String.[/color]
                    >
                    >I am loath to change the type of an object that undergoes no change,
                    >e.g. if the function is passed something that evaluates to the Number
                    >22, I don't want to spit out "22", although it really matters little, I
                    >suppose.[/color]

                    To have a leading zero, a result must be a string. IMHO, it is safer if
                    the type of a result is consistent; here, it is generally the case that
                    the result should be used as a string. I see possible problems with
                    LZ(Month)+LZ(Da y) otherwise - in Jan..Oct, and in the first 9 days of
                    any month, the leading zero means string, so the + means concatenate.
                    But, if LZ returns a Number when a zero is not added, for Nov 10-30 and
                    Dec 10-31 the + will mean addition.

                    [color=blue][color=green]
                    >> These might be better; String is probably cheap when applied to a string
                    >> :-
                    >> function lz(s) { var t = String(s)
                    >> return t.length==1 ? "0"+t : t } // or <2 ??
                    >>
                    >> function lz(s) { var t
                    >> return (t = String(s)).leng th==1 ? "0"+t : t } // ??[/color]
                    >
                    >lz("K") returns "0K", but it's not OK, at least in my book.[/color]

                    One might wish to have a two-digit result representing numbers N in
                    0..999, for example in a compact systematic name.

                    lz(N.toString(3 2).toUpperCase( )) will do that, giving 0K for N=20 and V7
                    for 999.

                    [color=blue]
                    > And I like
                    >the function to be somewhat descriptive, "strpad()" is a little obscure.[/color]

                    LZ is, of course, short for Leading Zero. It will commonly be used in
                    circumstances where shortness is useful; ISTM worth learning, if one
                    intends to use it. But this is scripting; a programmer using the method
                    is free to change the name, the identifiers used in it, the layout ... .

                    --
                    © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
                    <URL:http://jibbering.com/faq/> JL / RC : FAQ for news:comp.lang. javascript
                    <URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
                    <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.

                    Comment

                    Working...